exports.__esModule = true;

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

exports.default = class extends think.Service {
    constructor() {
        super();
        const db = this.db;
        this.typeGroupModel = db['sys_type_group'];
        this.typeModel = db['sys_type'];
        this.typeGroupModel.hasMany(this.typeModel, { foreignKey: 'typegroupid' });
    }

    /**
     * 缓存字典数据
     */
    initDictionaryCache() {
        var _this = this;

        return _asyncToGenerator(function* () {
            try {
                const attr = [['typecode', 'value'], ['typename', 'label'], ['other_attr', 'otherAttr']];
                const dataList = yield _this.typeGroupModel.findAll({
                    attributes: ['typegroupcode'],
                    include: [{ model: _this.typeModel, attributes: attr }]
                });
                const dictObj = {};
                for (var i = 0; i < dataList.length; i++) {
                    const key = dataList[i].typegroupcode;
                    const arr = dataList[i].sys_types;
                    dictObj[key] = arr;
                }

                if (think.redis.isReady()) {
                    const redisCli = think.redis.client;

                    //获取字典keys
                    let keys = yield redisCli.keys('dict:*');
                    //如果字典表有keys,则先清除缓存
                    if (keys.length !== 0) {
                        redisCli.del(keys);
                    }
                    //缓存字典表
                    for (let key in dictObj) {
                        redisCli.set(`dict:${key}`, JSON.stringify(dictObj[key]));
                    }
                } else {
                    throw new Error('连接redis失败,数据字典加载失败');
                }
                return dictObj;
            } catch (e) {
                return _this.exceptionService.handleError(e);
            }
        })();
    }

    /**
     * 构建字典数据结构
     * @returns {boolean}
     */
    buildDictData() {
        var _this2 = this;

        return _asyncToGenerator(function* () {
            try {
                const attr = [['typecode', 'value'], ['typename', 'label'], ['other_attr', 'otherAttr']];
                const dataList = yield _this2.typeGroupModel.findAll({
                    attributes: ['typegroupcode'],
                    include: [{ model: _this2.typeModel, attributes: attr }]
                });
                const Obj = {};
                for (var i = 0; i < dataList.length; i++) {
                    const key = dataList[i].typegroupcode;
                    const arr = dataList[i].sys_types;
                    Obj[key] = arr;
                }
                return Obj;
            } catch (err) {
                return _this2.exceptionService.handleError(err);
            }
        })();
    }

    findDictionaryList(data) {
        var _this3 = this;

        return _asyncToGenerator(function* () {
            data.start = (parseInt(data.page) - 1) * parseInt(data.pageSize);
            const Op = _this3.db.Sequelize.Op;
            let where = {};
            if (data.typegroupname && data.typegroupname !== undefined) {
                where.typegroupname = {
                    [Op.like]: '%' + data.typegroupname + '%'
                };
            }
            try {
                return yield _this3.typeGroupModel.findAndCountAll({
                    where: where,
                    limit: parseInt(data.pageSize),
                    offset: parseInt(data.start)
                });
            } catch (err) {
                return _this3.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 保存字典分组信息
     * data --{}
     */
    saveDicInfo(data) {
        var _this4 = this;

        return _asyncToGenerator(function* () {
            if (!data.id) {
                data.id = think.uuid('v1');
            }
            try {
                const old = yield _this4.typeGroupModel.findOne({
                    where: {
                        typegroupcode: data.typegroupcode
                    }
                });
                if (old && old.id !== data.id) {
                    return false;
                }
                yield _this4.typeGroupModel.upsert(data);
                return true;
            } catch (err) {
                return _this4.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 删除字典信息
     * data --Object
     * data.id --字典id String
     */
    delDicInfo(data) {
        var _this5 = this;

        return _asyncToGenerator(function* () {
            try {
                yield _this5.typeGroupModel.destroy({ where: data });
                yield _this5.typeModel.destroy({ where: { typegroupid: data.id } });
                return true;
            } catch (err) {
                return _this5.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 查找字典下的所有字典类型
     * @param groupId
     * @return list Array
     */
    findDicTypeList(groupId) {
        var _this6 = this;

        return _asyncToGenerator(function* () {
            try {
                return yield _this6.typeModel.findAll({ where: { typegroupid: groupId } });
            } catch (err) {
                return _this6.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 保存字典类型
     * @param data
     * @returns {Promise<*>}
     */
    saveDicTypeInfo(data) {
        var _this7 = this;

        return _asyncToGenerator(function* () {
            if (!data.id) {
                data.id = think.uuid('v1');
            }
            try {
                return yield _this7.typeModel.upsert(data);
            } catch (err) {
                return _this7.exceptionService.handleError(err);
            }
        })();
    }

    /**
     * 删除字典类型
     * @param childModel
     * @param foreignKey
     */
    delDicTypeInfo(data) {
        var _this8 = this;

        return _asyncToGenerator(function* () {
            try {
                return yield _this8.typeModel.destroy({ where: data });
            } catch (err) {
                return _this8.exceptionService.handleError(err);
            }
        })();
    }

};